<template>
  <div>
    <a-textarea placeholder="请输入聊天内容" :rows="4" v-model="name"/>
    <input type="file" @change="upload_qiniu">
    <a-button type="primary" @click="sendNews">发送</a-button>

    <br><br>
    <p v-for="i in ChatList" :key="i.id">
      <span v-show="i.withdraw==0">
        {{ i.name }} -- <img v-show='i.img!=null' :src="i.img" style="with:50px;height:50px;">
        <a-button type="dashed" v-show="i.send==uid" @click="put(i.id)">撤回</a-button>
      </span>
      <span v-show="i.withdraw==1">
        你撤回了一条消息 <font style="color: #1890ff">重新编辑</font>
      </span>

    </p>


  </div>

</template>

<script>
export default {
  name: "Chat",
  data() {
    return {
      ChatList: [],
      uid: localStorage.getItem('uid'),
      name: '',
      img_url: '',
      // 七牛去上传凭证
      uptoken: '',
    }
  },
  methods: {
    // 获取消息
    getChat() {
      this.$axios.get('/z/chat/')
        .then(res => {
          this.ChatList = res.data
        })
    },
    // 撤回消息
    put(id) {
      this.$axios.put('/z/chat/', {
        'id': id,
        'uid': this.uid
      })
        .then(res => {
          console.log(res.data.msg)
          this.getChat()
        })
    },
    // 发送消息
    sendNews() {
      this.$axios.post('/z/chat/', {
        'name': this.name,
        'img': this.img_url,
        'send': this.uid,
      })
        .then(res => {
          console.log(res.data.msg)
          this.getChat()
        })

    },
    // 七牛云
    get_uptoken() {
      this.$axios.get('/z/uptoken/').then(res => {
        this.uptoken = res.data.token
      })
    },
    // 七牛云上传
    upload_qiniu(e) {
      // 获取文件对象
      let file = e.target.files[0]
      // 声明参数
      let form_data = new FormData()
      // 将上传凭证添加参数
      form_data.append('token', this.uptoken)
      // 添加图片
      form_data.append('file', file)
      // 定制化axios  不携带cookie上传
      const axios_qiniu = this.$axios.create({withCredentials: false})
      // 发送请求
      axios_qiniu({
        method: 'post',
        url: 'http://up-z1.qiniu.com/',
        data: form_data,
        tiemout: 30000,

      }).then(res => {
        console.log(res)
        this.img_url = 'http://qq5y8xj19.hb-bkt.clouddn.com/' + res.data.key
      })
    },
  },
  mounted() {
    this.getChat()
    this.get_uptoken()
  }
}
</script>

<style scoped>

</style>
